﻿using System;
using System.Web;
using System.Web.Caching;
using Microsoft.IdentityModel.Protocols.WSFederation;

namespace CodeCounsel.SharePoint2010.DigiD
{
    static class SignInRequestCache
    {
        static readonly string _cacheKey = null;

        static SignInRequestCache()
        {
            _cacheKey = typeof(SignInRequestCache).Name;
        }

        public static void Add(string digiDRequestID, SignInRequestMessage requestMessage)
        {
            HttpRuntime.Cache.Add(
                GetCacheKey(digiDRequestID),
                requestMessage, 
                null, 
                DateTime.Now.Add(DigiDService.Local.DigiDRequestTimeout),
                Cache.NoSlidingExpiration, 
                CacheItemPriority.High, 
                null);
        }

        public static SignInRequestMessage Get(string digiDRequestID)
        {
            string key = GetCacheKey(digiDRequestID);
            SignInRequestMessage record = (SignInRequestMessage)HttpRuntime.Cache[key];
            if (record == null)
            {
                throw new DigiDException("DigiD request is no longer available");
            }
            HttpRuntime.Cache.Remove(key);
            return record;
        }

        static string GetCacheKey(string digiDRequestID)
        {
            return _cacheKey + "_" + digiDRequestID;
        }
    }
}
